<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/22
 * Time: 11:49
 */
namespace App\Models;

use App\Jobs\Elesticsearch;
use App\Jobs\InviteQueue;
use App\Services\Log;
use App\Services\UserService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\UserTicket;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\Redis;

/**
 * @param $MobileNo string 注册手机号
 * @param $referee string 推荐人
 * @param $unionid string 微信unionid
 * @param $openid string 微信openid
 * @param $is_offline bool 是否是线下
 * @param $introducer_reward int 是否进行奖励
 * @return array|bool
 */
class User extends Model{

    protected $table = 'users';
    public $timestamps = false;
    protected $primaryKey = 'id';

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    }

    public function _mediaStars() {
        return $this->hasMany('App\Models\MediaStar','uid');
    }

    public function register($MobileNo,$unionid,$openid,$password,$Invitation_code,$registration_id)
    {
        $mobile_unique_code = IT('mobile_unique_code',true,'移动设备唯一标识必填',10073);

        $name = '用户'.random_num(13);
        $userInfo = [
            'mobile' => $MobileNo,
            'name' => $name,
            'password' => md5($password),
            'status' => 1,
            'avatar'=> '',
            'download_time'    =>  time(),
            'created_at'    =>  date('Y-m-d H:i:s'),
            'updated_at'    =>  date('Y-m-d H:i:s'),
            'registration_id'    =>  $registration_id
        ];

        if(!empty($MobileNo)){
            //股东,会员手机号码检测
            $Shareholder_info=Shareholder::where([['mobile', '=', $MobileNo],['status', '=', '0'],['data_audit','=',1],['fund_audit','=',1]])->first(['mobile']);
            $member = MemberShip::where([['mobile','=',$MobileNo],['status', '=', '0']])->first(['mobile']);
            if($Shareholder_info)
                $userInfo['role'] = 1;
            if($member)
                $userInfo['membership'] = 1;
        }

        if($openid){
            $userInfo['openid'] = $openid;
        }

        DB::beginTransaction();
        $uid = DB::table('users')->insertGetId($userInfo);//插入成功返回id值
        // 注册环信账号
        if($uid){
            $hx_re_user = UserService::reg_hx_user($uid);
            if(!$hx_re_user){
                DB::rollback();  //回滚
                return false;
            }
            DB::commit();  //提交
        }

        // 待优化
        if ($uid) {
            $temp_arr = [];
            // 队列
            $temp_arr['uid'] = $uid;
            $temp_arr['operation_id'] = $MobileNo;
            $temp_arr['mobile_unique_code'] = $mobile_unique_code;
            $temp_arr['invitation_code'] = '';
            if(!empty($Invitation_code)){
                $temp_arr['invitation_code'] = $Invitation_code;
            }
            dispatch((new InviteQueue(['type'=>'2', 'data'=>$temp_arr]))->onQueue('invite'));

            // 队列   --添加搜索索引
            $params['uid'] = $uid;
            $params['name'] = $name;
            $params['mobile'] = $MobileNo;
            dispatch((new Elesticsearch(['type'=>'1', 'action'=>'add', 'data'=>$params]))->onQueue('eleasticsearch'));

            //注册成功将UID更新到user_tags表
            $tags_data =[
                'uid' => $uid,
            ];
            DB::table('user_tags')->insert($tags_data);

            //生成ticket入库
            $ticket = get_ticket($uid);
            if ($ticket) {
                return ['ticket' => $ticket, 'uid' => $uid, 'tags' => null, 'hx_username'=>$hx_re_user['username'], 'hx_password'=>$hx_re_user['password']];
            }
        }

        $invites = D('friend_invite')->where('mobile', $MobileNo)->get(['uid']);
        $date = time2date();
        $data = [];
        if ($invites) {
            foreach ($invites as $invite) {
                $_data = [$uid, $invite->uid];
                sort($_data);
                $data[] = ['uid' => $_data[0], 'friend_uid' => $_data[1], 'status' => 1, 'created_at' => $date, 'updated_at' => $date];
            }
            D('friend')->insert($data);
        }

        return false;
    }

    /**
     *  获取Vip身份字符串
     */
    static function getVipStr($vip_level)
    {

        switch ($vip_level) {
            case 0:
                return '普通用户';
                break;
            case 1:
                return '月度用户';
                break;
            case 2:
                return '年度用户';
                break;
            default:
                return '';
                break;
        }

    }

    /**
     * @param $ticket
     * @return mixed
     * @throws ApiException
     */
    static function getUserInfo($ticket)
    {
        if (!$ticket) {
            throw new ApiException('缺少参数ticket',0);
        }
        $user_ticket = UserTicket::where([ ['ticket','=',$ticket],['status','=',1] ])->first();
        if(!$user_ticket)
            throw new ApiException('用户未登录', 1000);

        return $user_ticket->_user;
    }

    public function _medias()
    {
        return $this->hasMany('App\Models\Media','uid')->where([['media.status', 1], ['media.is_delete', '=', 0], ['is_forward', '=', 0]]);
    }

    public function _mediaComments()
    {
        return $this->hasMany('App\Models\MediaComment','uid');
    }

    /**
     * 原来用户
     *
     * @return void
     * @date
     * @version v1.0
     */
    public function _fans_friends(){
        return $this->hasMany('App\Models\Friend','uid');
    }

    /**
     * 添加好友用户
     *
     * @return void
     * @date
     * @version v1.0
     */
    public function _follow_friends()
    {
        return $this->hasMany('App\Models\Friend','friend_id');
    }

    /*
     * 用户基础信息
     * */
    public static function get_user_rows_arr($uid)
    {
        $temp_arr = [];
        $key = 'user:info:'.$uid;
        if(!empty($uid)){
            if(!empty($user_detail = Redis::get($key)))
                return json_decode($user_detail, true);
            $rows = User::where([['id', '=', $uid]])->first();
            if(!empty($rows)){
                $temp_arr = $rows->toArray();
                unset($temp_arr['password'], $temp_arr['openid'], $temp_arr['app_openid'], $temp_arr['openid_default'], $temp_arr['unionid']);
                $expires_in = rand(3600, 3600*24);
                Redis::setex($key, $expires_in, json_encode($temp_arr));
            }
        }
        return $temp_arr;
    }

}